<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <!-- <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="queryParams.roleName"
                placeholder="请输入角色名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item> -->
            <el-form-item label="客户昵称" prop="customerNickname">
                <el-input v-model="queryParams.customerNickname" placeholder="请输入客户昵称" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <!-- <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:role:edit']"
                >修改</el-button
              > -->
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" >删除</el-button>
            </el-col>
            <el-col v-if="user == 'admin'" :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="roleList" @sort-change="paixu" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="创建时间" prop="createTime" />
            <el-table-column label="渠道" prop="attribute" :show-overflow-tooltip="true" width="150" />


            <el-table-column fixed="right" label="操作" align="center" width="200" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:role:edit']">修改</el-button> -->
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                      >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 分配角色数据权限对话框 -->
        <el-dialog @close="guanbishoukan" :title="title" :destroy-on-close="true" :close-on-click-modal="false"
            :visible.sync="xunkong">
            <el-form :model="kesuwanfrom" :rules="kesuwanfromre" ref="xundanfrom" label-width="180px"
                class="demo-ruleForm">
                <p style="color: red; text-align: center">
                    <!-- 注：重复添加同一用户，金额会累加 -->
                </p>
                <el-form-item prop="attribute" label="渠道">
                    <el-input v-model="kesuwanfrom.attribute" placeholder="请输入渠道昵称" clearable style="width: 240px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!-- <el-form-item prop="balance" label="金额">
                    <el-input v-model="kesuwanfrom.balance" placeholder="请输入金额" clearable style="width: 240px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button @click="xunkong = false">取 消</el-button>
                <el-button type="primary" @click="xundan">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog @close="guanbishoukan" :title="title" :destroy-on-close="true" :close-on-click-modal="false"
            :visible.sync="cahkan">
            <el-table v-loading="loading" :data="ddjilu" @selection-change="handleSelectionChange">
                <el-table-column label="订单号" prop="orderNumber" />
                <el-table-column label="订单金额" prop="money" :show-overflow-tooltip="true" width="150" />
                <el-table-column label="类型" prop="workTwo" :show-overflow-tooltip="true" width="150">
                    <template slot-scope="scope">
                        <span>
                            {{ scope.row.fromType == 0 ? "储值" : "消费" }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="余额" prop="remainingSum"> </el-table-column>

                <!-- <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:role:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:role:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column> -->
            </el-table>

            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button @click="cahkan = false">关闭</el-button>
                <!-- <el-button type="primary" @click="cahkan = false">确 定</el-button> -->
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { addRole, updateRole, dataScope } from "@/api/system/role";

import {
    DELETEhuzhilist,
    getchuzhilist,
    putchuzhilist,
    addchuzhilist,
    getjilvs,
    getqudao,
    asddgetqudao,
    deletequdao
} from "@/api/new";

export default {
    name: "Role",
    dicts: ["sys_normal_disable"],
    data() {
        return {
            cahkan: false,
            ketui: "",
            jiaojie: "",
            dai: "",
            ddjilu: [],
            // 遮罩层
            loading: true,
            // 选中数组
            xunkong: false,
            ids: [],
            xunkong: false,
            // 非单个禁用
            single: true,
            user: this.$store.state.user.name,
            now: "",
            hounow: 0,
            // 非多个禁用
            kesuwanfrom: {

                attribute: ''
            },

            kesuwanfromre: {
                attribute: [
                    { required: true, message: "渠道不能为空", trigger: "blur" },
                ],

            },
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 角色表格数据
            roleList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否显示弹出层（数据权限）
            openDataScope: false,
            menuExpand: false,
            menuNodeAll: false,
            deptExpand: true,
            deptNodeAll: false,
            // 日期范围
            dateRange: [],
            // 数据范围选项

            // 查询参数
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                customerNickname: "",
                sortField: '',
                orderingRule: ''
            },
            // 表单参数
            form: {},
            defaultProps: {
                children: "children",
                label: "label",
            },
            // 表单校验
            rules: {
                roleName: [
                    { required: true, message: "角色名称不能为空", trigger: "blur" },
                ],
                roleKey: [
                    { required: true, message: "权限字符不能为空", trigger: "blur" },
                ],
                roleSort: [
                    { required: true, message: "角色顺序不能为空", trigger: "blur" },
                ],
            },
        };
    },
    created() {
        this.getList();
    },

    methods: {
        paixu(e, d) {
            let xu = "";
            if (e.order == "descending") xu = "desc";
            if (e.order == "ascending") xu = "asc";
            let a = e.prop.replace(/([A-Z])/g, "_$1").toLowerCase();

            this.queryParams.sortField = a;
            this.queryParams.orderingRule = xu;
            this.getList();
        },
        chalook(row) {
            this.cahkan = true;
            getjilvs({ pageNo: 1, pageSize: 10000, clientID: row.attributeId }).then(
                (response) => {
                    this.ddjilu = response.rows;
                }
            );
        },
        timestampToDateString(timestamp) {
            // 创建一个新的Date对象
            var date = new Date(timestamp);

            // 使用getFullYear(), getMonth() + 1, getDate() 获取年、月、日
            // 注意：getMonth() 返回的是0-11，所以需要+1来得到正常的月份
            var year = date.getFullYear();
            var month = ("0" + (date.getMonth() + 1)).slice(-2); // 使用slice来确保月份是两位数
            var day = ("0" + date.getDate()).slice(-2); // 同上，确保日期是两位数

            // 拼接成 yyyy-MM-dd 格式
            return `${year}-${month}-${day}`;
        },
        xundan() {
            this.$refs["xundanfrom"].validate((valid) => {
                if (valid) {
                    if (this.title !== "添加") {
                        asddgetqudao(this.kesuwanfrom).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.xunkong = false;
                            this.getList();
                        });
                    } else {
                        asddgetqudao(this.kesuwanfrom).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.xunkong = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 查询角色列表 */
        getList() {
            this.loading = true;
            getqudao(this.queryParams).then((response) => {
                this.roleList = response.rows;
                // this.total = response.total;
                this.loading = false;
            });
        },

        // 取消按钮
        cancel() {
            this.open = false;
        },
        // 取消按钮（数据权限）
        cancelDataScope() {
            this.openDataScope = false;
        },
        // 表单重置

        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.attributeId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleDataScope":
                    this.handleDataScope(row);
                    break;
                case "handleAuthUser":
                    this.handleAuthUser(row);
                    break;
                default:
                    break;
            }
        },
        // 树权限（展开/折叠）

        guanbishoukan() {
            this.kesuwanfrom = {
                customerNickname: "",
                balance: "",
            };
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.xunkong = true;
            this.title = "添加";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.xunkong = true;

            this.kesuwanfrom.customerNickname = row.customerNickname;

            this.kesuwanfrom.balance = row.balance;
            this.kesuwanfrom.attributeId = row.attributeId;
            this.title = "修改";
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const roleIds = row.attributeId || this.ids;
            this.$modal
                .confirm("是否确认删除数据项？")
                .then(function () {
                    return deletequdao(roleIds);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "system/clientPay/export",
                {
                    ...this.queryParams,
                },
                `客户储值${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>